import { DataService } from '@/services/core/DataService';
import { IntModel } from '@/services/core';

import { HttpUtil } from '@/utils/HttpUtil';
import { DataObject } from '@/utils/types';
import { Mapping } from '@/components/Table/types';
import { PickByValueExact } from 'utility-types';

export const associationList = async <Id, Model, Key extends keyof Model>(
  service: DataService<Model, Id>,
  key: Key,
  label: keyof PickByValueExact<Model, string>
): Promise<Mapping<Model[Key]>[]> => {
  const resp = await service.selectAll();
  const list: Model[] = HttpUtil.getList(resp);
  return list.map(v => ({
    label: v[label] as unknown as string,
    value: v[key],
  }));
};

export const association = async <A extends DataObject, B, BId, Key extends string | number | symbol>(
  bService: DataService<B, BId>,
  aList: A[],
  aKey: keyof A,
  bKey: keyof B,
  bLabel: keyof B,
  aLabel: Key,
  defaultValue: string
): Promise<(A & Record<Key, string>)[]> => {
  const resp = await bService.selectAll();
  const bList: B[] = HttpUtil.getList(resp);
  return (aList as (A & Record<Key, string>)[]).map(a => {
    const b = bList.find(b => (b[bKey] as unknown) === (a[aKey] as unknown));
    if (b) {
      (a[aLabel] as string) = b[bLabel] as unknown as string;
    } else {
      (a[aLabel] as string) = defaultValue;
    }
    return a;
  });
};
